#include <iostream>
#include <fstream>
#include <iomanip>
#include "TH1.h"
#include "TH2.h"
#include "TFile.h"
#include "TTree.h"
#include "TCanvas.h"
#include "TStyle.h"

using namespace std;

struct PMT{
  int nhit;
  float x,y,z,px,py,pz;
  int isref;
};
struct Track{
  int pdgcode;
  float Edep;
  float PathLength;
};

void positionEff(){
  gStyle->SetOptStat(000000);

  TFile* fread=new TFile("../outputFiles/alpha6.root");
  if(!fread){cout<<"No File"<<endl;return;}
  
  TTree*  tree=(TTree*)fread->Get("tree");
  

  int EvNum;
  Track InitTrack;
  PMT JPMThit[100000],MPMThit[100000];
  int nPhoton,nJPMThits, nMPMThits;
  float EDEP;

  tree->SetBranchAddress("EvNum",&EvNum);
  tree->SetBranchAddress("Track",&InitTrack);
  tree->SetBranchAddress("nPhoton",&nPhoton);
  tree->SetBranchAddress("nJPMThits",&nJPMThits);
  tree->SetBranchAddress("JPMThit",JPMThit);
  tree->SetBranchAddress("nMPMThits",&nMPMThits);
  tree->SetBranchAddress("MPMThit",MPMThit);
  tree->SetBranchAddress("EDEP",&EDEP);

  TH2F *hPosEff_J=new TH2F("hPosEff_J","hPosEff_J",30,-150,150,35,-150,200);
  TH2F *hPosEff_M=new TH2F("hPosEff_M","hPosEff_M",30,-150,150,35,-150,200);
  TH1F *hEff_J=new TH1F("hEff_J","hEff_J",100,0,20);
  TH1F *hEff_M=new TH1F("hEff_M","hEff_M",100,0,20);

  int nEvent = tree->GetEntries();
  cout<<"Number of Events = "<<nEvent<<endl;

  for(int iev=0;iev<nEvent;iev++){
    tree->GetEntry( iev );

    int iz = iev / 21 % 18 ;
    int ir = iev % 21 ;
    float zpos = iz*10.-20.;
    float rpos = ir*10.-120;
    
    hPosEff_J->Fill( rpos,zpos,nJPMThits/(float)nPhoton*100 );
    hPosEff_M->Fill( rpos,zpos,nMPMThits/(float)nPhoton*100 );
    hEff_J->Fill( nJPMThits/(float)nPhoton*100 );    
    hEff_M->Fill( nMPMThits/(float)nPhoton*100 );    
  }

  TCanvas *c1=new TCanvas("c1","c1",1000,800);
  c1->Divide(2,1);
  c1->cd(1);
  hPosEff_J->SetXTitle("x [mm]");
  hPosEff_J->SetYTitle("z [mm]");
  hPosEff_J->Draw("colz");
  c1->cd(2);
  hPosEff_M->SetXTitle("x [mm]");
  hPosEff_M->SetYTitle("z [mm]");
  hPosEff_M->Draw("colz");

  TCanvas *c2=new TCanvas("c2","c2",1000,800);
  c2->Divide(2,1);
  c2->cd(1);
  hEff_J->SetXTitle("Effciency [%]");
  hEff_J->SetYTitle("NEV");
  hEff_J->Draw();
  c2->cd(2);
  hEff_M->SetXTitle("Effciency [%]");
  hEff_M->SetYTitle("NEV");
  hEff_M->Draw();

  cout<<"Ave eff(J) = "<<hEff_J->GetMean()<<endl;
  cout<<"Ave eff(M) = "<<hEff_M->GetMean()<<endl;

}
